﻿#include "ServerListModel.h"
#include <QDebug>


ServerListModel *ServerListModel::Singleton()
{
    static ServerListModel * singleton = new ServerListModel();
    return singleton;
}

ServerListModel::ServerListModel(QObject *parent ) : QAbstractListModel(parent)
{
    QVector<quint16> portVec;
    for (quint16 i = 30000; i < 30000+10; ++i)
    {
        portVec << i;
    }
    udpBroadcastClient.InitClient(portVec);
    connect(&udpBroadcastClient, &UdpBroadcast::signalNewServer, this, &ServerListModel::addServer);
    //udpBroadcastClient.InitServer("kkk", "http://www.baidu.com", portVec);
    // 扫描
    udpBroadcastClient.scan();

#if 0
    addServer(tr("pc-baidu"), tr("http://www.baidu.com"));
    addServer(tr("pc-sina"), tr("https://www.sina.com.cn"));
    addServer(tr("pc-localhost"), tr("http://127.0.0.1"));
#endif

}

int ServerListModel::rowCount(const QModelIndex &) const
{
    return mServerInfoList.count();
}

QVariant ServerListModel::data(const QModelIndex &index, int role) const
{
    if (index.row() < rowCount())
    {
        switch (role) {
        case ServerNameRole: return mServerInfoList.at(index.row()).serverName;
        case ServerAddrRole: return mServerInfoList.at(index.row()).serverAddr;

        default: return QVariant();
        }
    }
    return QVariant();
}

QHash<int, QByteArray> ServerListModel::roleNames() const
{
    static const QHash<int, QByteArray> roles {
        { ServerNameRole, "serverName" },
        { ServerAddrRole, "serverAddr" },
    };
    return roles;
}


QVariantMap ServerListModel::get(int row) const
{
    const ServerInfo serverInfo = mServerInfoList.value(row);
    return { {"serverName", serverInfo.serverName}
        , {"serverAddr", serverInfo.serverAddr}
    };
}

void ServerListModel::addServer(const QString& serverName, const QString& serverAddr)
{
    qDebug() << "addServer:" << serverName << ", " << serverAddr;
    for (int row = 0; row < mServerInfoList.count(); ++row)
    {
        if(serverName == mServerInfoList.at(row).serverName
                && serverAddr == mServerInfoList.at(row).serverAddr)
        {
            dataChanged(index(row, 0), index(row, 0), {ServerNameRole, ServerAddrRole});
            return ;
        }
    }

    int row = mServerInfoList.size();
    beginInsertRows(QModelIndex(), row, row);
    mServerInfoList.insert(row, ServerInfo(serverName, serverAddr));
    endInsertRows();

}

void ServerListModel::remove(int row)
{
    if (row < 0 || row >= mServerInfoList.count())
    {
        return;
    }
    beginRemoveRows(QModelIndex(), row, row);
    mServerInfoList.removeAt(row);
    endRemoveRows();
}

void ServerListModel::clear()
{
    int count = mServerInfoList.count();
    if(count > 0)
    {
        beginRemoveRows(QModelIndex(), 0, count-1);
        mServerInfoList.clear();
        endRemoveRows();
    }
}

void ServerListModel::scanServer()
{
    this->clear();
    this->udpBroadcastClient.scan();
}

